/*
 * 百度在线网络技术（北京）有限公司拥有本软件版权2021并保留所有权利。
 * Copyright 2021, Baidu.com,Inc 2:Baidu Online Network Technology (Beijing) Co.,Ltd,
 * All rights reserved.
 */

package com.azdebugit.map.est;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class TestMap {
    public static void main(String[] args)
            throws IOException {
        //举个读取一本小说的例子
        String file = "test.txt";
        Map<Character, Integer> map =
                countAll(file, "utf-8");
        int all = 0;
        Collection<Integer> values = map.values();

        for (int n : values) {
            all += n;
        }
        List<Map.Entry<Character, Integer>> list =//像这里使用Map.Entry内部类，类似的应该怎么理解，运用？？？
                new ArrayList<Map.Entry<Character, Integer>>(
                        map.entrySet());
        Collections.sort(list, new
                Comparator<Map.Entry<Character, Integer>>() {
                    private int dir = -1;

                    @Override
                    public int compare(Map.Entry<Character, Integer> o1,
                                       Map.Entry<Character, Integer> o2) {
                        return dir * (o1.getValue() - o2.getValue());
                    }
                });
        for (int i = 0; i < 10; i++) {
            Map.Entry<Character, Integer> entry = list.get(i);
            char ch = entry.getKey();
            int n = entry.getValue();
            System.out.println(
                    ch + ":" + n + "个  " + ((double) n / all) * 100);
        }
        System.out.println("不重复字数）：" + map.size());
        System.out.println("文字总数：" + all);
    }

    public static Map<Character, Integer> countAll(
            String file, String encoding)
            throws IOException {
        InputStreamReader in =
                new InputStreamReader(
                        new BufferedInputStream(
                                new FileInputStream(file)), encoding);
        Set<Character> set =
                new HashSet<Character>();
        set.add(',');
        set.add('　');
        set.add('，');
        set.add('。');
        set.add('：');
        set.add(':');
        //set.add(':');
        set.add('\n');
        set.add('\r');

        Map<Character, Integer> map =
                new HashMap<Character, Integer>();
        int c;
        int i = 0;
        while ((c = in.read()) != -1) {
            char ch = (char) c;
            if (set.contains(ch)) {//忽略掉回车换行，标点符号那些
                System.out.println(i++);
                continue;
            }
            Integer n = map.get(ch);
            map.put(ch, n == null ? 1 : n + 1);
        }

        in.close();
        return map;
    }
}
